class LocalPaging {

    constructor(data, limit = 10) {
        if (limit < 1) {
            limit = 10;//自动屏蔽异常
        }
        this.data = data || [];
        this.limit = limit;
        this.page = 1;
        this.maxPage = 1;
        this.pageData = [];
        if (this.data.length > 0) {
            this.compute();
            this.selectPage(1);
        }

    }

    /**
     * 重新加载数据源
     * @param data
     */
    init(data) {
        this.data = data || [];
        this.page = 1;
        if (this.data.length > 0) {
            this.compute();
            this.selectPage();
        }
    }

    /**
     * 重置分页大小
     * @param limit
     */
    resetLimit(limit) {
        if (limit < 1) {
            limit = 10;//自动屏蔽异常
        }
        this.limit = limit;
        this.page = 1;
        if (this.data.length > 0) {
            this.compute();
            this.selectPage();
        }
    }


    /**
     * 计算总页数
     */
    compute() {
        this.maxPage = Math.ceil(this.data.length / this.limit);
    }

    /**
     * 读取指定分页数据
     */
    selectPage(pageNum) {
        const num = pageNum || this.page;
        this.page = num;
        const start = (num - 1) * this.limit;
        let end = start + this.limit - 1;
        if (end > this.data.length - 1) {
            end = this.data.length - 1;
        }
        const result = [];
        for (let i = start; i <= end; i++) {
            result.push(this.data[i]);
        }
        this.pageData = result;

        return result;
    }

    /**
     * 读取上一页数据
     */
    lastPage() {
        if (this.page > 1) {
            this.page--;
        }
        return this.selectPage();
    }

    /**
     * 读取下一页数据
     */
    nextPage() {
        if (this.page < this.maxPage) {
            this.page++;
        }
        return this.selectPage();
    }
}


export {
    LocalPaging
}

export default LocalPaging;
